<?php
/**
 * Created by PhpStorm.
 * User: dreamy
 * Date: 2021-12-13
 * Time: 15:16
 */
namespace common\services;

use common\models\StockBalance;
use common\models\StockBalanceDetail;
use common\models\StockBalanceHouse;
use common\models\StockProduct;
use common\models\StockWarehouse;
use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\data\Pagination;

/**
 * Class TallyStockBalanceService
 * @package common\services
 * 库存（进销存）库存余额管理
 */
class TallyStockBalanceService extends BaseService
{
    /**
     * 按仓库维度统计的库存统计
     * @param       $tallyId
     * @param array $condition
     *
     * @return array
     */
    public static function summaryHouse($tallyId,$condition=[])
    {
        // 先获取仓库列表 按正常分页走
        $houseList = TallyStockWarehouseService::getList($tallyId,$condition);
        if(!empty($houseList['data'])) {
            $houseIds = ArrayHelper::getColumn($houseList['data'],'id'); // 本次需要统计的仓库ID

            // 根据仓库 通过in查询获取sum的 group数据
            $groupData = StockBalanceHouse::find()->select('house_id,sum(`balance_money`) as `total_balance`,sum(`pure_num`) as `total_num`')->where([
                'tally_id' => $tallyId,
            ])->andFilterWhere([
                'in', 'house_id', $houseIds
            ])->groupBy('house_id')->asArray()->all();

            // var_dump($groupData);
            //  die;

            $tempHouseMoney = [];
            $tempHouseNum = [];
            foreach ($groupData as $gv) {
                $tempHouseMoney[$gv['house_id']] = $gv['total_balance'];
                $tempHouseNum[$gv['house_id']] = $gv['total_num'];
            }

            // 重新融合数据
            foreach ($houseList['data'] as $hk => $hv) {
                $houseId = $hv['id'];
                $houseMoney = 0;
                $houseNum = 0;
                if(isset($tempHouseMoney[$houseId])) {
                    $houseMoney = $tempHouseMoney[$houseId];
                }
                if(isset($tempHouseNum[$houseId])) {
                    $houseNum = $tempHouseNum[$houseId];
                }
                $houseList['data'][$hk]['total_balance'] = ToolService::moneyFormat($houseMoney);
                $houseList['data'][$hk]['total_num'] = ToolService::moneyFormat($houseNum);
            }
            return $houseList;
        }else {
            return $houseList;
        }
    }

    /**
     * 按产品维度统计的库存
     * @param       $tallyId
     * @param array $condition
     *
     * @return array
     */
    public static function summaryProduct($tallyId,$condition=[])
    {
        $where = [
            'tally_id' => $tallyId,
        ];
        $query = StockBalance::find()->where($where);

        // 其他条件 的筛选器拼接 如关键词（这里只用来搜索标题）
        $keywords = ArrayHelper::getValue($condition,'keywords','');

        if($keywords){
            $query->andFilterWhere(['like','product_title',$keywords]);
        }

        // 分页相关
        $count = $query->count();
        // 构造分页对象
        $pageSize = $_SERVER['PAGE_SIZE'] ?: 10 ;
        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $count
        ]);
        $pagination->validatePage=false;

        // 从DB获取
        $balanceList = $query->orderBy('balance_money desc')
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->asArray()
            ->all();

        // 返回带分页数据
        return [
            'data'       => $balanceList ?: [],
            'pageInfo'   => [
                'totalCount' => intval($count) ,
                'pageSize'   => intval($pageSize)
            ]
        ];
    }

    /**
     * 获取某个仓库下的产品库存统计
     * @param $tallyId
     * @param $houseId
     * @param $condition
     *
     * @return array|bool
     */
    public static function houseDetail($tallyId,$houseId,$condition=[])
    {
        // 先检查这个仓库是否存在
        $houseInfo = StockWarehouse::find()->where([
            'id' => $houseId,
            'tally_id' => $tallyId,
        ])->asArray()->one();

        if(!$houseInfo) {
            self::setError('仓库数据不存在');
            return false;
        }

        // 库存明细的查询条件
        $where = [
            'tally_id' => $tallyId,
            'house_id' => $houseId,
        ];

        // 直接查看统计表即可 不需要再重新运算 (只匹配出库存数量大于0的 说明存在库存)(库存金额>0的)
//        $query = StockBalanceHouse::find()->where($where)->andWhere(['>', 'pure_num', 0])->andWhere(['>', 'balance_money', 0]);
        $query = StockBalanceHouse::find()->where($where)->andWhere(['>', 'pure_num', 0]);
        $count = $query->count();
        // 构造分页对象
        $pageSize = $_SERVER['PAGE_SIZE'] ?: 10 ;
        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $count
        ]);
        $pagination->validatePage = false;
        $balanceList = $query->offset($pagination->offset)->limit($pagination->limit)->asArray()->all();
        // 批量获取productInfo 数据
        $productIds = ArrayHelper::getColumn($balanceList,'product_id');
        // 根据仓库 通过in查询获取sum的 group数据
        $groupData = StockProduct::find()->where(['tally_id' => $tallyId,])->andFilterWhere(['in', 'id', $productIds])->asArray()->all();
        $tempProduct = [];
        foreach ($groupData as $gv) {
            $tempProduct[$gv['id']] = $gv;
        }

        foreach ($balanceList as $bk => $bv) {
            $balanceList[$bk]['pure_n'] = $bv['pure_num'];
            $balanceList[$bk]['money'] = $bv['balance_money'];
            $productId = $bv['product_id'];
            // 填充产品信息
            $balanceList[$bk]['product_title'] = $tempProduct[$productId]['title'];
            $balanceList[$bk]['product_spec'] = $tempProduct[$productId]['spec'];
            $balanceList[$bk]['product_unit'] = $tempProduct[$productId]['unit'];
            $balanceList[$bk]['product_cost_price'] = $tempProduct[$productId]['cost_price'];
        }

        // 返回带分页数据
        return [
            'data'       => $balanceList ?: [],
            'pageInfo'   => [
                'totalCount' => intval($count) ,
                'pageSize'   => intval($pageSize)
            ]
        ];
    }

    /**
     * 获取某个仓库下的产品库存统计
     * @param $tallyId
     * @param $houseId
     * @param $condition
     *
     * @return array|bool
     */
//    public static function houseDetail($tallyId,$houseId,$condition=[])
//    {
//        // 先检查这个仓库是否存在
//        $houseInfo = StockWarehouse::find()->where([
//            'id' => $houseId,
//            'tally_id' => $tallyId,
//        ])->asArray()->one();
//
//        if(!$houseInfo) {
//            self::setError('仓库数据不存在');
//            return false;
//        }
//
//        // 库存明细的查询条件
//        $where = [
//            'tally_id' => $tallyId,
//            'house_id' => $houseId,
//        ];
//
//        // 要查找sum的 groupBy productId的统计数据
//        $query = StockBalanceDetail::find()
//            ->select('product_id')
//            ->groupBy('product_id')
//            ->where($where);
//
//        // 分页相关
//        $count = $query->count();
//        // 构造分页对象
//        $pageSize = $_SERVER['PAGE_SIZE'] ?: 10 ;
//        $pagination = new Pagination([
//            'defaultPageSize' => $pageSize,
//            'totalCount' => $count
//        ]);
//        $pagination->validatePage=false;
//
//        // 从DB获取
//        $balanceList = $query->select('`product_id`, sum(`in_num` - `out_num`) AS `pure_n`,
//SUM(IF(`in_num` > 0, `balance_money`, -1*balance_money)) AS `money`')
//            ->offset($pagination->offset)
//            ->limit($pagination->limit)
////            ->having('money > 0')
//            ->asArray()
//            ->all();
//
////        print_r($balanceList);
////        die;
//        // 批量获取productInfo 数据
//        $productIds = ArrayHelper::getColumn($balanceList,'product_id');
//        // 根据仓库 通过in查询获取sum的 group数据
//        $groupData = StockProduct::find()->where([
//            'tally_id' => $tallyId,
//        ])->andFilterWhere([
//            'in', 'id', $productIds
//        ])->asArray()->all();
//
//        $tempProduct = [];
//        foreach ($groupData as $gv) {
//            $tempProduct[$gv['id']] = $gv;
//        }
//
//        foreach ($balanceList as $bk => $bv) {
//            $productId = $bv['product_id'];
//            // 填充产品信息
//            $balanceList[$bk]['product_title'] = $tempProduct[$productId]['title'];
//            $balanceList[$bk]['product_spec'] = $tempProduct[$productId]['spec'];
//            $balanceList[$bk]['product_unit'] = $tempProduct[$productId]['unit'];
//            $balanceList[$bk]['product_cost_price'] = $tempProduct[$productId]['cost_price'];
//        }
//
////            var_dump($groupData);
////            die;
//
//        $tempHouseMoney = [];
//        foreach ($groupData as $gv) {
//            $tempHouseMoney[$gv['house_id']] = $gv['total_balance'];
//        }
//
//        // 返回带分页数据
//        return [
//            'data'       => $balanceList ?: [],
//            'pageInfo'   => [
//                'totalCount' => intval($count) ,
//                'pageSize'   => intval($pageSize)
//            ]
//        ];
//    }

    /**
     * 获取产品明细库存数据
     * @param       $tallyId
     * @param       $productId
     * @param array $condition
     *
     * @return array|bool
     */
    public static function productDetail($tallyId,$productId,$condition=[])
    {
        // 库存明细的查询条件
        $where = [
            'tally_id' => $tallyId,
            'product_id' => $productId,
        ];
        $oderByStr = 'balance_money desc';
        $query = StockBalanceHouse::find()
            ->where($where)->andFilterWhere([
                '>', 'pure_num', 0
            ]);
        // 分页相关
        $count = $query->count();
        // 构造分页对象
        $pageSize = $_SERVER['PAGE_SIZE'] ?: 10 ;
        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $count
        ]);
        $pagination->validatePage=false;

        // 从DB获取
        $balanceList = $query->orderBy($oderByStr)
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->asArray()
            ->all();

        // 返回带分页数据
        return [
            'data'       => $balanceList ?: [],
            'pageInfo'   => [
                'totalCount' => intval($count) ,
                'pageSize'   => intval($pageSize)
            ]
        ];
    }

    /**
     * 产品入库 / 出库
     * @param       $tallyId
     * @param       $optType
     * @param array $condition
     *
     * @throws
     * @return bool
     */
    public static function operateHouse($tallyId,$optType,$condition=[])
    {
        $productDetail = ArrayHelper::getValue($condition,'product_detail');
        if(empty($productDetail)) {
            self::setError('添加产品不能为空');
            return false;
        }
        $houseId = ArrayHelper::getValue($condition,'house_id');
        $houseIdFrom = ArrayHelper::getValue($condition,'house_id_from','');

        if($optType == 'trans' && !$houseIdFrom) {
            self::setError('请选择调出仓库');
            return false;
        }

        // 检查这个仓库是否存在
        $houseInfo = StockWarehouse::find()->where([
            'id' => $houseId,
            'tally_id' => $tallyId,
        ])->asArray()->one();
        if(!$houseInfo) {
            self::setError('仓库数据不存在');
            return false;
        }

        // 调配过程的调出仓库
        $houseInfoFrom = [];
        if($optType == 'trans') {
            $houseInfoFrom = StockWarehouse::find()->where([
                'id' => $houseIdFrom,
                'tally_id' => $tallyId,
            ])->asArray()->one();
            if(!$houseInfoFrom) {
                self::setError('仓库数据不存在');
                return false;
            }
        }

        // 记账日期
        $tallyDate = ArrayHelper::getValue($condition,'tally_date');
        if(!$tallyDate) {
            $tallyDate = date('Y-m-d');
        }

        // 一次性拉取全部产品基础信息
        $productIds = ArrayHelper::getColumn($productDetail,'product_id');
        $groupData = StockProduct::find()->where([
            'tally_id' => $tallyId,
        ])->andFilterWhere([
            'in', 'id', $productIds
        ])->asArray()->all();
        if(count($groupData) != count($productIds)) {
            self::setError('部分产品数据不存在 请检查');
            return false;
        }
        $productTempData = [];
        foreach ($groupData as $gv) {
            $productId = $gv['id'];
            $productTempData[$productId] = $gv;
        }

        // 开启事务
        $transaction = Yii::$app->db->beginTransaction();

        $loopFlag = true;

        // 遍历产品 执行处理添加逻辑
        foreach ($productDetail as $pv) {
            // 产品名称 + 产品ID + 入口数量 + 成本价折算 + 入库时间
            $productId = $pv['product_id'];
            $costPrice = $pv['cost_price']; // 成本价
            // 产品信息
            $productInfo =  $productTempData[$productId];

            $inNum = 0;
            $outNum = 0;
            $inNumFrom = 0;
            $outNumFrom = 0;
            if($optType == 'in') {
                $inNum = $pv['num'];
                $outNum = 0;
            }else if($optType == 'out') {
                $inNum = 0;
                $outNum = $pv['num'];
                // 这里检查 仓库里某产品的库存
                $stockNum = self::getStockProductNum($tallyId,$houseId,$productId);
                if($outNum > $stockNum) {
                    self::setError('产品【'.$productInfo['title'].'】超出最大库存：'.$stockNum);
                    break;
                }
            }else if($optType == 'trans') {
                $inNum = $pv['num'];
                $outNum = 0;
                $inNumFrom = 0;
                $outNumFrom = $pv['num'];

                // 这里检查 仓库里某产品的库存
                $stockNum = self::getStockProductNum($tallyId,$houseIdFrom,$productId);
                if($outNum > $stockNum) {
                    self::setError('产品【'.$productInfo['title'].'】超出最大库存：'.$stockNum);
                    break;
                }
            }

            $balanceMoney = ToolService::moneyFormat($pv['num'] * $costPrice);
            // 准备入库数据
            $balanceDetailFormData = [
                'tally_id' => $tallyId,
                'product_id' => $productId,
                'product_title' => $productInfo['title'],
                'product_spec' => $productInfo['spec'],
                'product_unit' => $productInfo['unit'],
                'product_cost_price' => $costPrice,
                'house_id' => $houseId,
                'house_title' => $houseInfo['title'],
                'in_num' => $inNum,
                'out_num' => $outNum,
                'balance_money' => $balanceMoney,
                'tally_date' => $tallyDate,
            ];

            $addRes = self::addDetail($balanceDetailFormData);

            // 中断循环 事务回滚
            if(!$addRes) {
                $loopFlag = false;
                break;
            }

            // 调拨情况下 继续写入调出记录
            if($optType == 'trans') {
                $balanceDetailFormData['house_id'] = $houseIdFrom;
                $balanceDetailFormData['house_title'] = $houseInfoFrom['title'];
                $balanceDetailFormData['in_num'] = $inNumFrom;
                $balanceDetailFormData['out_num'] = $outNumFrom;
                $addFromRes = self::addDetail($balanceDetailFormData);
                // 中断循环 事务回滚
                if(!$addFromRes) {
                    $loopFlag = false;
                    break;
                }
            }
        }

        //  任务出错了 事务回滚
        if(!$loopFlag) {
            $transaction->rollBack();
            return false;
        }

        $transaction->commit();

        // 触发总表 产品 仓库 二维统计数据的更新
        foreach ($productDetail as $pv) {
            $productId = $pv['product_id'];
            $productInfo =  $productTempData[$productId];
            self::syncProductBalance($tallyId,$productId,$productInfo);

            // 触发总表 仓库维度数据更新
            self::syncProductHouseBalance($tallyId,$houseId,$houseInfo,$productId,$productInfo);
            if($optType == 'trans') {
                self::syncProductHouseBalance($tallyId,$houseIdFrom,$houseInfoFrom,$productId,$productInfo);
            }
        }

        return true;
    }

    /**
     * 获取某仓库里某产品的净库存
     * @param $tallId
     * @param $houseId
     * @param $productId
     *
     * @return mixed
     */
    protected static function getStockProductNum($tallId,$houseId,$productId)
    {
        $stockInfo = StockBalanceHouse::find()->where([
            'tally_id' => $tallId,
            'house_id' => $houseId,
            'product_id' => $productId
        ])->asArray()->one();
        return ArrayHelper::getValue($stockInfo,'pure_num',0);
    }

    /**
     * 写入一条明细数据
     * @param $balanceDetailFormData
     *
     * @return bool
     */
    public static function addDetail($balanceDetailFormData)
    {
        $model = new StockBalanceDetail();
        $model->load($balanceDetailFormData,'');
        if ($model->validate() && $model->save()) {
            return true;
        }else {
            Yii::error('Stock operateHouse insert error:'.current($model->getFirstErrors()).';post:'.Json::encode($balanceDetailFormData,JSON_UNESCAPED_UNICODE));
            self::setError(current($model->getFirstErrors()));
            return false;
        }
    }

    /**
     * 统计detail表中的数据统计 然后写入/更新总表
     * @param $tallyId
     * @param $productId
     * @param $productInfo
     *
     * @return bool
     */
    public static function syncProductBalance($tallyId,$productId,$productInfo)
    {
        // 查看总表是否存在
        $balanceModel = StockBalance::find()->where([
            'tally_id' => $tallyId,
            'product_id' => $productId
        ])->one();

        // 统计出产品的入库总金额
        $inInfo = StockBalanceDetail::find()->select('sum(`in_num`) as in_c,sum(`balance_money`) as in_m')->where([
            'tally_id' => $tallyId,
            'product_id' => $productId
        ])->andFilterWhere(['>','in_num',0])->asArray()->one();

        // 统计出产品的出库总金额
        $outInfo = StockBalanceDetail::find()->select('sum(`out_num`) as out_c,sum(`balance_money`) as out_m')->where([
            'tally_id' => $tallyId,
            'product_id' => $productId
        ])->andFilterWhere(['>','out_num',0])->asArray()->one();

        // 计算出总数据
        $totalIn = ToolService::moneyFormat($inInfo['in_c']);
        $totalOut = ToolService::moneyFormat($outInfo['out_c']);
        $totalPure = ToolService::groupMathAdd([
            $totalIn,
            -1*$totalOut
        ]);

        // 这里金额的计算不再用过程量加减、而是使用库存商品的成本价字段 * 净量
//        $totalMoney = ToolService::groupMathAdd([
//            $inInfo['in_m'],
//            -1*$outInfo['out_m'],
//        ]);
        $productCostPrice = ArrayHelper::getValue($productInfo,'cost_price',0);
        $totalMoney = ToolService::moneyFormat($totalPure * $productCostPrice);

        if($balanceModel) {
            // 总数量
            $balanceModel->in_num = $totalIn;
            $balanceModel->out_num = $totalOut;
            $balanceModel->pure_num = $totalPure;
            // 总金额
            $balanceModel->balance_money = $totalMoney;
            // 执行更新
            $res = $balanceModel->save();
            if($res) {
                return true;
            }else {
//                print_r($balanceModel->getFirstErrors());
                self::setError(current($balanceModel->getFirstErrors()));
                return false;
            }
        }else {
            // 执行新增
            $balanceFormData = [
                'tally_id' => $tallyId,
                'product_id' => $productId,
                'product_title' => ArrayHelper::getValue($productInfo,'title',''),
                'product_spec' => ArrayHelper::getValue($productInfo,'spec',''),
                'product_unit' => ArrayHelper::getValue($productInfo,'unit',''),
                'product_cost_price' => $productCostPrice,
                'in_num' => $totalIn,
                'out_num' => $totalOut,
                'pure_num' => $totalPure,
                'balance_money' => $totalMoney,
            ];
            $model = new StockBalance();
            $model->load($balanceFormData,'');
            if ($model->validate() && $model->save()) {
                return true;
            }else{
                // print_r($model->getFirstErrors());
                Yii::error('Stock Balance Sync insert error:'.current($model->getFirstErrors()).';post:'.Json::encode($balanceFormData,JSON_UNESCAPED_UNICODE));
                self::setError(current($model->getFirstErrors()));
                return false;
            }
        }
    }

    /**
     * 统计某仓库里某个商品的统计数据
     * @param       $tallyId
     * @param       $houseId
     * @param array $houseInfo
     * @param       $productId
     * @param array $productInfo
     *
     * @return bool
     */
    public static function syncProductHouseBalance($tallyId,$houseId,$houseInfo,$productId,$productInfo)
    {
        // 统计出产品的入库总金额
        $inInfo = StockBalanceDetail::find()->select('sum(`in_num`) as in_c,sum(`balance_money`) as in_m')->where([
            'tally_id' => $tallyId,
            'product_id' => $productId,
            'house_id' => $houseId,
        ])->andFilterWhere(['>','in_num',0])->asArray()->one();

        // 统计出产品的出库总金额
        $outInfo = StockBalanceDetail::find()->select('sum(`out_num`) as out_c,sum(`balance_money`) as out_m')->where([
            'tally_id' => $tallyId,
            'product_id' => $productId,
            'house_id' => $houseId,
        ])->andFilterWhere(['>','out_num',0])->asArray()->one();

        // 计算出总数据
        $totalIn = ToolService::moneyFormat($inInfo['in_c']);
        $totalOut = ToolService::moneyFormat($outInfo['out_c']);
        $totalPure = ToolService::groupMathAdd([
            $totalIn,
            -1*$totalOut
        ]);

        // 这里金额的计算不再用过程量加减、而是使用库存商品的成本价字段 * 净量
//        $totalMoney = ToolService::groupMathAdd([
//            $inInfo['in_m'],
//            -1*$outInfo['out_m'],
//        ]);
        $productCostPrice = ArrayHelper::getValue($productInfo,'cost_price',0);
        $totalMoney = ToolService::moneyFormat($totalPure * $productCostPrice);

        // 查看总表是否存在
        $balanceModel = StockBalanceHouse::find()->where([
            'tally_id' => $tallyId,
            'product_id' => $productId,
            'house_id' => $houseId,
        ])->one();

        if($balanceModel) {
            // 总数量
            $balanceModel->pure_num = $totalPure;
            // 总金额
            $balanceModel->balance_money = $totalMoney;
            // 执行更新
            $res = $balanceModel->save();
            if($res) {
                return true;
            }else {
//                 print_r($balanceModel->getFirstErrors());
                self::setError(current($balanceModel->getFirstErrors()));
                return false;
            }
        }else {
            // 执行新增
            $balanceFormData = [
                'tally_id' => $tallyId,
                'product_id' => $productId,
                'house_id' => $houseId,
                'house_title' => ArrayHelper::getValue($houseInfo,'title',''),
                'product_title' => ArrayHelper::getValue($productInfo,'title',''),
                'product_spec' => ArrayHelper::getValue($productInfo,'spec',''),
                'product_unit' => ArrayHelper::getValue($productInfo,'unit',''),
                'pure_num' => $totalPure,
                'balance_money' => $totalMoney,
            ];
            $model = new StockBalanceHouse();
            $model->load($balanceFormData,'');
            if ($model->validate() && $model->save()) {
                return true;
            }else{
                // print_r($model->getFirstErrors());
                Yii::error('Stock Balance Sync insert error:'.current($model->getFirstErrors()).';post:'.Json::encode($balanceFormData,JSON_UNESCAPED_UNICODE));
                self::setError(current($model->getFirstErrors()));
                return false;
            }
        }
    }

    /**
     * 获取库存余额的统计数据
     * @param       $tallyId
     *
     * @return array
     */
    public static function getSummary($tallyId)
    {
        $totalMoney = StockBalance::find()->where([
            'tally_id' => $tallyId
        ])->sum('balance_money');
        return [
            'total_balance_money' => ToolService::moneyFormat($totalMoney)
        ];
    }

    /**
     * 获取账本下 库存流失的的分页记录
     * @param       $tallyId
     * @param array $condition
     *
     * @return array
     */
    public static function flowList($tallyId,$condition=[])
    {
        $query = self::getFlowQuery($tallyId,$condition);
        // 分页相关
        $count = $query->count();
        // 构造分页对象
        $pageSize = $_SERVER['PAGE_SIZE'] ?: 10 ;
        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $count
        ]);
        $pagination->validatePage=false;

        // 默认按创建时间倒叙
        $orderByStr = 'id desc';
        // 如果有筛选账单时间就按账单时间排序
        if(isset($condition['begin_date']) || isset($condition['end_date'])) {
            $orderByStr = 'tally_date desc,id desc';
        }

        // 从DB获取
        $productList = $query->orderBy($orderByStr)
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->asArray()
            ->all();

        // 返回带分页数据
        return [
            'data'       => $productList ?: [],
            'pageInfo'   => [
                'totalCount' => intval($count) ,
                'pageSize'   => intval($pageSize)
            ]
        ];
    }



    /**
     * 获取账本下 库存流失的的分页记录
     * @param       $tallyId
     * @param array $condition
     *
     * @return array
     */
    public static function flowListWithPage($tallyId,$condition=[])
    {
        $query = self::getFlowQuery($tallyId,$condition);
        // 分页相关

        // 默认按创建时间倒叙
        $orderByStr = 'id desc';
        // 如果有筛选账单时间就按账单时间排序
        if(isset($condition['begin_date']) || isset($condition['end_date'])) {
            $orderByStr = 'tally_date desc,id desc';
        }

        if(self::checkIsHasField($condition,'is_cai')){
            //采购订单IN
            $query->andFilterWhere([
                '<>','stock_record_id',0
            ]);
        }
        // 从DB获取
        $productList = $query->orderBy($orderByStr)
            ->asArray()
            ->all();

        $rData = [
            'pages'=>$productList,

        ];
        $file_str = ['in_num','out_num'];
        $rData['nums'] = bcadd(array_sum(array_column($productList,$file_str[$condition['type_net']])),0,2);
        $rData['balance'] = bcadd(array_sum(array_column($productList,'balance_money')),0,2);
        return $rData;
    }

    /**
     * @param       $tallyId
     * @param array $condition
     *
     * @return \yii\db\ActiveQuery
     */
    protected static function getFlowQuery($tallyId,$condition=[])
    {
        $where = [
            'tally_id'   => $tallyId,
        ];

        // 从DB获取
        $query = StockBalanceDetail::find()
            ->select('*')
            ->where($where);

        // 项目ID
        $projectId = ArrayHelper::getValue($condition,'project_id','');
        if($projectId){
            $query->andFilterWhere(['=','project_id',$projectId]);
        }


        $productId = ArrayHelper::getValue($condition,'product_id','');
        if($productId){
            $query->andFilterWhere(['=','product_id',$productId]);
        }

        // 设置默认空 方便下面做判断
        if(!isset($condition['begin_date'])) $condition['begin_date'] = '';
        if(!isset($condition['end_date'])) $condition['end_date'] = '';

        // 时间段查询 包含右时间边界
        if($condition['begin_date'] != '' && $condition['end_date'] != '') {
            $condition['end_date'] = date('Y-m-d',strtotime('+1 day',strtotime($condition['end_date'])));
            $query->andFilterWhere(['between','tally_date',$condition['begin_date'], $condition['end_date']]);
        }
        if($condition['begin_date'] != '' && $condition['end_date'] == '') {
            $query->andFilterWhere(['>','tally_date',$condition['begin_date']]);
        }
        if($condition['begin_date'] == '' && $condition['end_date'] != '') {
            $condition['end_date'] = date('Y-m-d',strtotime('+1 day',strtotime($condition['end_date'])));
            $query->andFilterWhere(['<','tally_date',$condition['end_date']]);
        }

        // 备注关键词
        $memo = ArrayHelper::getValue($condition,'memo','');
        if($memo){
            $query->andFilterWhere(['like','memo',$memo]);
        }
        return $query;
    }

    public static function delFlow($tallyId, $condition)
    {
        $itemInfo = StockBalanceDetail::find()->where($condition);
        if(!$itemInfo->exists()){
            self::setError("数据不存在");
        }
        $itemInfo = $itemInfo->one();




        print_r($itemInfo);exit;
//        if($query-)
    }

}
